using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SimpleFeedback.Data;
using SimpleFeedback.Models;

namespace SimpleFeedback.Controllers
{
    public class FeedbackController(Context context) : Controller
    {
        private readonly Context _context = context;
        private const int pageSize = 10;

        public IActionResult Send()
        {
            return View();
        }
        [Route("/Done")]
        public IActionResult Done(Feedback feedback)
        {
            if (string.IsNullOrEmpty(feedback.Title) && string.IsNullOrEmpty(feedback.Content))
                return View();
            feedback.Created = DateTime.Now;
            _context.Feedbacks.Add(feedback);
            _context.SaveChanges();
            return View();
        }

        [Authorize]
        [Route("/ViewSubmitted/{pageIdx?}")]
        public IActionResult ViewSubmitted(int pageIdx) 
        {
            if (pageIdx <= 0)
                return RedirectToAction(nameof(ViewSubmitted), new { pageIdx = 1 });
            var count = _context.Feedbacks.Count();
            int skip = (pageIdx - 1) * pageSize;
            if (count > 0 && count <= skip)
            {
                int maxPageIdx = count / pageSize + 1;
                if (count % pageSize == 0)
                    maxPageIdx--;
                return RedirectToAction(nameof(ViewSubmitted), new { pageIdx = maxPageIdx });
            }
            var list = _context.Feedbacks
                .OrderByDescending(x=>x.Created)
                .Skip(skip).Take(pageSize).ToList();
            return View(new FeedbackViewModel(list, pageIdx));
        }

        [Route("/mi")]
        public IActionResult Mi()
        {
            _context.Database.Migrate();
            return Ok("Ok");
        }
    }
}
